package org.douxiaoban.client.app;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.preference.PreferenceManager;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.PopupWindow;
import android.widget.Toast;
import com.mobclick.android.MobclickAgent;
import com.mobclick.android.UmengFeedback;
import com.mobclick.android.UmengFeedbackListener;
import org.douxiaoban.client.R;
import org.douxiaoban.client.activity.NormalLoginActivity;
import org.douxiaoban.client.api.ApiKey;
import org.douxiaoban.client.api.DoubanApi;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Random;

/**
 * Created by IntelliJ IDEA.
 * User: huangzhongkun
 * Date: 11-3-23
 * Time: 上午12:29
 */
public class App extends Application {

    public static SharedPreferences sharedPreferences;

    private static DoubanApi doubanApi;

    public static Bitmap myAvatar;
    public static int max = 20;
    public static int mMailMax = 20;
    public static String currentUserId ;
    public static String currentUserName;
    public static String userId ;
    public static String username;
    public static int version_sdk;

    public static String API_KEY;
    public static String API_SECRET;

    public static Boolean isWVGA = false;
    public static Boolean isLogin = false;

    public static int NETWORK_STATUS;

    @Override
    public void onCreate() {
        super.onCreate();    //Super Method super.onCreate();
        //doubanApi = new DoubanApi();
        //sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);

        if(getRadomApiKey())
            loadPrefenencce();

        getCurrentDesity();
        if(isEnableNetwork())
            getNetworkType();
    }

    @Override
    public void onTerminate() {
        super.onTerminate();    //Super Method super.onTerminate();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        //Super Method super.onConfigurationChanged(newConfig);
    }

    @Override
    public void onLowMemory() {
        super.onLowMemory();    //Super Method super.onLowMemory();
    }

    public static DoubanApi getDouanApiInstance(){
         return doubanApi;
    }


    public Boolean getRadomApiKey(){
        sharedPreferences = PreferenceManager.
                       getDefaultSharedPreferences(this);
        API_KEY= sharedPreferences.getString(Assistant.SETTING_ACCESS_API_KEY,null);
        API_SECRET = sharedPreferences.getString(Assistant.SETTING_ACCESS_API_SECRET,null);

        if(API_KEY ==null||API_SECRET==null ||API_KEY.equals("")|| API_SECRET.equals("")){
            int position = (int)(Math.random()* (ApiKey.API_KEY_COLLECTION.size()-1));
            Log.v("position:","|"+position);

            Object[] key =  ApiKey.API_KEY_COLLECTION.keySet().toArray();
           Iterator iterator = ApiKey.API_KEY_COLLECTION.entrySet().iterator();

            int i = 1;
            while (iterator.hasNext()){
                Map.Entry entry =(Map.Entry)iterator.next();
                if(i == position){
                   doubanApi = new DoubanApi(Assistant.APP_NAME,
                           (String)entry.getKey(),(String)entry.getValue());
                    sharedPreferences.edit().putString(Assistant.
                            SETTING_ACCESS_API_KEY,(String)entry.getKey()).commit();
                    sharedPreferences.edit().putString(Assistant.
                            SETTING_ACCESS_API_SECRET,(String)entry.getValue()).commit();
                    return false;
                }
                i++;
            }

        }else{
            doubanApi = new DoubanApi(Assistant.APP_NAME,API_KEY,API_SECRET);
            isLogin = true;
            return true;
        }
        return false;
    }

    public void loadPrefenencce() {
        sharedPreferences = PreferenceManager.
                getDefaultSharedPreferences(this);

        doubanApi.ACCESS_TOKEN= sharedPreferences.
                getString(Assistant.SETTING_ACCESS_TOKEN_KEY, null);
        doubanApi.ACCESS_SECRET= sharedPreferences.
                getString(Assistant.SETTING_ACCESS_TOKEN_SECRET, null);
        doubanApi.setAccessToken();
        doubanApi.UID = sharedPreferences.
                getString(Assistant.SETTING_UID,null);
        doubanApi.USER_NAME = sharedPreferences.
                getString(Assistant.SETTING_UNAME,null);
        userId = doubanApi.UID;
        username = doubanApi.USER_NAME;
     }



    public void mentOptions(int itemId,Activity activity){

          switch (itemId){
            case R.id.menu_logout:
                logout(activity);
                break;
            case R.id.menu_feedback:
                MobclickAgent.openFeedbackActivity(activity);
                break;

            case R.id.menu_quit:
                quit();
                break;
            case R.id.menu_about:
            	about();	
                break;
            default:
                break;
        }
    }

    public  void logout(Activity activity){
         sharedPreferences = PreferenceManager.
                       getDefaultSharedPreferences(this);
        sharedPreferences.edit().putString(Assistant.SETTING_ACCESS_TOKEN_KEY,null).commit();
        sharedPreferences.edit().putString(Assistant.SETTING_ACCESS_TOKEN_SECRET,null).commit();
        sharedPreferences.edit().putString(Assistant.SETTING_ACCESS_API_KEY,null).commit();
        sharedPreferences.edit().putString(Assistant.SETTING_ACCESS_API_SECRET,null).commit();
        sharedPreferences.edit().putString(Assistant.SETTING_UID,null).commit();

        Intent logoutInent = new Intent();
        logoutInent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        logoutInent.setClass(activity, NormalLoginActivity.class);
        activity.startActivity(logoutInent);
    }
    
    
    private void about(){
    	LayoutInflater flater = LayoutInflater.from(this);
//    	View view = flater.inflate(R.layout.about, null);
//    	PopupWindow popupWindow = new PopupWindow(view, LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT, true);
//		popupWindow.setBackgroundDrawable(new BitmapDrawable());
//		popupWindow.showAtLocation(view,Gravity.TOP | Gravity.LEFT, 0, 0);
//		popupWindow.update();

    }
    public void setting(){

    }

    public void quit(){
        // sdk 2.1 = api 7
        if(version_sdk<7){
            Intent startMain = new Intent(Intent.ACTION_MAIN);
            startMain.addCategory(Intent.CATEGORY_HOME);
            startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(startMain);
            System.exit(0);
        }else{
            ActivityManager am =(ActivityManager)getSystemService(Context.ACTIVITY_SERVICE);
            am.restartPackage(getPackageName());
        }
    }

    public void getSDKVersionNumber() {
     try {
         version_sdk = Integer.valueOf(android.os.Build.VERSION.SDK);
    } catch (NumberFormatException e) {
        version_sdk = 0;
    }
    }

    public Boolean isEnableNetwork(){
        ConnectivityManager connectivityManager =(ConnectivityManager)this.
                getSystemService(Context.CONNECTIVITY_SERVICE);

        if(connectivityManager ==null || connectivityManager.getActiveNetworkInfo() ==null
                || !connectivityManager.getActiveNetworkInfo().isAvailable()){
            Toast.makeText(this,getString(R.string.network_disable),2000).show();
            return false;
        }
        return true;
    }

    public void getNetworkType(){
        ConnectivityManager connectivityManager =(ConnectivityManager)this.
                getSystemService(Context.CONNECTIVITY_SERVICE);

        NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();

        if(networkInfo.getType() == ConnectivityManager.TYPE_WIFI)
            NETWORK_STATUS = Assistant.WIFI;

        if(networkInfo.getType() == ConnectivityManager.TYPE_MOBILE)
            NETWORK_STATUS = Assistant.GPRS;

    }

    public static int dip2px(Context context, float dipValue){
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int)(dipValue * scale + 0.5f);
    }

    public static int px2dip(Context context, float pxValue){
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int)(pxValue / scale + 0.5f);
    }


    public void getCurrentDesity(){
        Configuration config = getResources().getConfiguration();
        if((config.screenLayout&Configuration.SCREENLAYOUT_SIZE_MASK)
           == Configuration.SCREENLAYOUT_SIZE_LARGE){
            isWVGA = true;
            Log.v("screen_size:","WVGA");

        }
        Log.v("screen_size:",config.screenLayout+"");
    }


}
